import axios, {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosError,
  AxiosResponse,
  AxiosRequestConfig
} from "axios"
import { useUserStore } from "@/stores/modules/user"
import { Snackbar, LoadingBar } from "@varlet/ui"

const TOKEN_KEY = "token"

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  },
  timeout: 20 * 1000,
  withCredentials: true
})

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    LoadingBar.start()
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers[TOKEN_KEY] = userStore.token
    }
    return config
  },
  (err: AxiosError) => {
    LoadingBar.error()
    return Promise.reject(err)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse<Result>) => {
    // const userStore = useUserStore()
    const res = response.data
    if (!res) return response
    switch (res.code) {
      case 0:
      case "0":
      case 200:
      case "200": {
        LoadingBar.finish()
        return response
      }
      case 401: {
        //TODO 401 鑒權判斷
        return response
      }
      default: {
        const msg = res.info || res.msg || "未知错误"
        Snackbar(msg)
        return response
        // return Promise.reject(msg)
      }
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

export async function http<T = any, K = any>(
  config: AxiosRequestConfig<T>
): Promise<ResultData<T, K>> {
  const res = await service.request(config)
  return res.data
}

export interface Result<T = any> {
  code: number | string
  page?: T
  msg: string
  info: string
  hlsAddress?: string
  webVoiceTalkUrl?: string
}

export interface ResultData<T = any, K = any> extends Result<K> {
  data: T
}
